package com.ruibang.glass.common.utils;


import com.ruibang.glass.common.utils.validateannotation.NotBlank;
import com.ruibang.glass.common.utils.validateannotation.ObjectScope;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Optional;


public class ValidationUtils {
    /**
     * 自定义 验证注解 字符串不能为空
     */
    public static class NotBlankValidation implements ConstraintValidator<NotBlank, String> {

        private String message;

        public void initialize(NotBlank notBlank) {
            this.message = notBlank.message();
        }

        @Override
        public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
            if (s == null || s.trim().length() == 0) {
                constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
                return false;
            }
            return true;
        }
    }

    /**
     * 自定义 验证注解 字符串必须属于 某个范围内
     */
    public static class ObjectScopeValidation implements ConstraintValidator<ObjectScope, Object> {

        private String message;

        private String[] valueStr;

        private int[] valueInt;

        public void initialize(ObjectScope stringScope) {
            this.message = stringScope.message();
            this.valueStr = stringScope.valueStr();
            this.valueInt = stringScope.valueInt();
        }

        @Override
        public boolean isValid(Object s, ConstraintValidatorContext constraintValidatorContext) {

            if (valueStr.length > 0) {

                if (!Optional.ofNullable(s).isPresent() || !Arrays.stream(valueStr).anyMatch(v -> s.equals(v))) {

                    constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();

                    return false;
                }
            }


            if (valueInt.length > 0) {

                if (!Optional.ofNullable(s).isPresent() || !Arrays.stream(valueInt).anyMatch(v -> ((Integer) s).equals(v))) {

                    constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();

                    return false;

                }
            }

            return true;

        }
    }
}
